/*************************************************
 *FileName:      index.js
 *Description:   主页.js
 *Others:        陈灿
 *************************************************/
    /*
     * 启动
     */
    mui.init();
    mui('.mui-scroll-wrapper').scroll({
        indicators: false,      //是否显示滚动条 默认为true
        deceleration: 0.003,    //阻尼系数,系数越小滑动越灵敏 默认0.0006
        bounce: true           //是否启用回弹 默认true
    });
    
    /*
     * 防止底部菜单来回返回
     */
    mui.plusReady(function(){ 
        var wv=plus.webview.currentWebview();
        // 关闭侧滑返回功能
        wv.setStyle({'popGesture':'none'});
    
        var old_back = mui.back;
        var clickNum = 0;
        mui.back = function() {
            clickNum++;
            if(clickNum > 1) {
                plus.runtime.quit(); //关闭应用
            } else {
                mui.toast('再按一次退出应用', {
                    duration: 2000,
                    type: 'div'
                })
            }
            setTimeout(function() {
                clickNum = 0
            }, 2000);
            return false;
        }
    });
    /*
     * 变量初始化
     */
    var uid = localStorage.replace_uid;
    var token = localStorage.replace_token
    var page = 3;
    var olist = '';
    localStorage.welcome=false;
    var othis ;
    var oindex;
    var onebox ;
    /*
     * HTML5+准备完成
     */
    
    window.addEventListener('refreshindex', function(e){//执行刷新个人中心
        getUsersInfo();
        message();
        if(localStorage.guideurl!='null'){
            common.pageTransition(localStorage.guideurl)
        }
    });
    
    window.addEventListener('share',function(e){
        $('.share-box').fadeIn();
        $('.popover2').css({display:'block'});
        invitefrands();
    });
    
    window.addEventListener('myvoice',function(e){
        $('.index .popover').fadeIn();
        $('.index .mycenter').css({'left':'0'});
    });
    
    window.addEventListener('exits', function(e){//执行刷新
        exitlogin();
    });
    /*
     * 主程序
     */ 
    $(document).ready(function() 
    {
        //绑定多个tap跳转页面
        bindTaps(['editdata','signin','handlersharp','myprop','handler','agency','pm','set','grade','membercenter','notecase','notecase2','myfans','attention','myfriend','attestation','dataattestation','appointment','redemption','taskcenter','securitycenter']);
        //样式加载
        pagecss();
        getlist(null,1);
        getlist(null,2);
        getlist(null,3);
    });
    /**
     * pagecss
     * 样式加载
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    function pagecss(){
        mui.plusReady(getUsersInfo)
        mui.plusReady(message)
        mui.plusReady(function() {
            setInterval(updateNoticeNum, 30 * 1000) // 30s 实时更新消息
        })
        common.format();
        setTimeout(function(){
            console.log("sss"+localStorage.screens)
            if(localStorage.screens!='false'){
                pgwelcome();
            }else if(localStorage.guideurl!='null'){
                common.pageTransition(localStorage.guideurl)
            }
        },500)
        $('.signin .yp').text('YP: '+localStorage.replace_uid)
        $('.index .mui-pull-right').on('tap',function(){ 
            $('.index .popover').css({'display':'block'});
            $('.index .message').css({'display':'block'});
            setTimeout(function(){
                $('.index .message').css({'right':'0'});
            },100)
            message();
        })
        $('.index .mui-pull-left').on('tap',function(){
            $('.index .popover').css({'display':'block'});
            $('.index .mycenter').css({'display':'block'});
             setTimeout(function(){
                $('.index .mycenter').css({'left':'0'});
            },100)
            getUsersInfo();
        })
        
        $('.index').on('tap','.search',function(){
            $(this).hasClass('active') ? common.pageTransition('search.html'): mui.toast('只有VIP用户才能搜索!');
        })
        
        $('.index .message').on('tap','li .tab-img img',function(){
            var ofid = $(this).parents('li').attr('data-id');
            if(ofid){
                common.pageTransition('personal.html?friend_uid='+ofid)
            }
            return false;
        })
        
         /*****消息,个人中心 start*****/
        $('.index .message .tab a').on('tap',function(){
            $(this).addClass('pitch').siblings().removeClass();
            magindex=$(this).index();
            $('.message .mui-scroll-wrapper').eq(magindex).css({display:'block'}).siblings('.mui-scroll-wrapper').css({display:'none'});
        })
        $('.index .popover').on('tap',function(){
            mui('.mycenter .mui-scroll-wrapper').scroll().scrollTo(0,0,10);
            mui('.message .scroll2').scroll().scrollTo(0,0,10);
            mui('.message .scroll3').scroll().scrollTo(0,0,10);
            $('.index .popover').css({'display':'none'})
            $('.index .message').css({'right':'-80%'});//点击遮罩隐藏消息页
            $('.index .mycenter').css({'left':'-80%'});//点击遮罩隐藏个人中心页 
            setTimeout(function(){
                $('.index .message').css({'display':'none'});//点击遮罩隐藏消息页
                $('.index .mycenter').css({'display':'none'});//点击遮罩隐藏个人中心页 
            },200)
        })
        /*****消息,个人中心 end*****/
       
       
        $('.index').on('swipeleft','.chat-box .chatli',function(){
            $(this).css({left:'-3rem'})
        })
        $('.index').on('swiperight','.chat-box .chatli',function(){
            $(this).css({left:'0'})
        })
        $('.message').on('tap','li .delect',function(){
            var fid =$(this).parents('li').attr('data-id'); 
            var rid =$(this).parents('li').attr('ord-id'); 
            var othis = $(this).parents('li');
            rid ? chatstate(fid,rid,othis) : chatstate(fid,'0',othis);
            return false;
        })
        
        $('.scroll3').on('swipeleft','.box li',function(){
            $(this).css({left:'-3rem'})
        })
        $('.scroll3').on('swiperight','.box li',function(){
            $(this).css({left:'0'})
        })
        
        
    var startx, starty, endx, endy; //获得角度
    function getAngle(angx, angy) {
        return Math.atan2(angy, angx) * 180 / Math.PI;
    };
    //根据起点终点返回方向 1向上 2向下 3向左 4向右 0未滑动
    function getDirection(startx, starty, endx, endy) {
        var angx = endx - startx;
        var angy = endy - starty;
        var result = 0;
        //如果滑动距离太短
        if (Math.abs(angx) < 2 && Math.abs(angy) < 2) {
            return result;
        }
        var angle = getAngle(angx, angy);
        if ((angle >= 135 && angle <= 180) || (angle >= -180 && angle < -135)) {
            result = 3;
        } else if (angle >= -45 && angle <= 45) {
            result = 4;
        }
        return result;
    }   
    $(".index").on("touchstart",'.box-one', function(e) {//    手指接触屏幕
        startx = e.originalEvent.touches[0].pageX;
        starty = e.originalEvent.touches[0].pageY;
    }).on("touchmove", '.box-one',function(e) {//手指离开屏幕
        endx = e.originalEvent.changedTouches[0].pageX;
        $(this).css({marginLeft:(endx-startx)});
    }).on("touchend", '.box-one',function(e) {
        endx = e.originalEvent.changedTouches[0].pageX;
        endy = e.originalEvent.changedTouches[0].pageY;
        var direction = getDirection(startx, starty, endx, endy);
        var othis =$(this);
        switch (direction) {
            case 3:
                //向左
                $(this).css({transform:'translate(-160%,0)'});
                setTimeout(function(){
                    $('.box-two').addClass('box-one').removeClass('box-two');
                    $('.box-three').addClass('box-two').removeClass('box-three');
                    othis.removeClass('box-one').addClass('box-three').removeAttr('style');
                    getlist(othis,page++);
                },200)
                break;
            case 4:
                $(this).css({transform:'translate(60%,0)'});
                setTimeout(function(){
                    $('.box-two').addClass('box-one').removeClass('box-two');
                    $('.box-three').addClass('box-two').removeClass('box-three');
                    othis.removeClass('box-one').addClass('box-three');
                    $('.index-box .box').removeAttr('style');
                    getlist(othis,page++);
                },200) 
                //向右
                break;
            default:
                othis.removeAttr('style');
        }
    })
    
    
        
        
        
        $('.index').on('tap','.mp-user',function(){
            var othisuid =$(this).attr('data-id');
            common.pageTransition('personal.html?friend_uid='+othisuid);
        })//个人详情跳转
        
        
        $('.index').on('tap','.grade',function(){
            $('.promit').css({display:'block'});
            $('.poimit-table1').fadeIn();
        })
        
        $('.promit').on('tap',function(){
            $(this).css({display:'none'});
            $('.poimit-table1').fadeOut();
            $('.table-view').fadeOut();
        })
        
        var othid;
        $('.index').on('tap','.open',function(){
            othid = $(this).attr('data-pid');
            if(othid){
                $('.table-view3').fadeIn()
            }else{
                mui.confirm('解绑之后您的约会功能将关闭,<br />需重新完成约会认证，确定解绑?','提示',['确定','取消'],function(e){
                    if(e.index==0){parentopen('0');}
                },'div');
            }
        })
        
        $('.index').on('tap','.dataattestation .table-view-cell-a1',function(){
            $('.table-view3').fadeOut()
            mui.confirm('解绑之后您的约会功能将关闭,<br />需重新完成约会认证，确定解绑?','提示',['确定','取消'],function(e){
                if(e.index==0){parentopen(othid);}
            },'div');
        })
        
        $('.index').on('tap','.dataattestation .table-view-cell-a2',function(){
            $('.table-view3').fadeOut()
            mui.confirm('解绑之后您的约会功能将关闭,<br />需重新完成约会认证，确定解绑?','提示',['确定','取消'],function(e){
                if(e.index==0){parentopen('0');}
            },'div');
        })
        
        $('.index').on('tap','.convertcdk',function(){
            $('.table-view1').fadeIn();
            $('.promit').css({display:'block'});
        })
        
         $('.index').on('tap','.editdata .table-view-cell-a',function(){//失去焦点
            $('.table-view-cell-input').blur();
        })
         
        $('.table-view1').on('tap','.table-view-cell-affirm',function(){
            $('.table-view').fadeOut();
            $('.promit').css({display:'none'});
            var ocdk =$(this).parents('.table-view1').find('.table-view-cell-input').val();
            convertcdk(ocdk);
            $(this).parents('.table-view1').find('.table-view-cell-input').val('');
        })
        
        $('.table-view-cell-cancel').on('tap',function(){
            $('.table-view').fadeOut();
            $('.promit').css({display:'none'});
        })
        
        $('.share-box').on('tap','.share-delect',function(){
            $('.share-box').fadeOut();
            $('.popover2').css({display:'none'});
            getUsersInfo();
        })
        
        $('.content').on('tap','.invite',function(){
            $('.share-box').fadeIn();
            $('.popover2').css({display:'block'});
            invitefrands();
        })
        
        $('.share-box').on('tap','.share-a',function(){
            $('.share-box').fadeIn();
            $('.popover2').css({zIndex:'100003'});
            $('.share-link').css({bottom:'0'});
            $('.popover2').on('tap',function(){
                $('.popover2').css({zIndex:'100001'});
                $('.share-link').css({bottom:'-5.2rem'});
            })
            // share();
        })
        
        $('.message').on('tap','li',function(){
            var ouid = $(this).attr('data-id');
            var ofid = $(this).attr('ord-id');
            if( $(this).hasClass('setmsg')){
                setRead(function() {
                  common.pageTransition('messages.html');
                })
            }else if($(this).hasClass('chatli')){
                common.pageTransition('chat.html?thatid='+ouid+'');
            }else if($(this).hasClass('strangeli')){
                common.pageTransition('chat.html?thatid='+ouid+'&&state='+ofid);
            }
        })

        $('.index').on('tap', '#circlefriends', function(){
          articleRead(function() {
            common.pageTransition('circlefriends.html');
          })
        })
        
        $('.voice-editdata').on('tap',function(){
            $('.voice-em').css({display:'block'})
            $('.con-voice-img').css({display:'none'})
        })
        
        $('.exit').on('tap',function(){
            mui.confirm('确定退出登录？','提示',['确定','取消'],function(e){
                if(e.index==0){
                    exitlogin();
                }
            },'div')
        })
    }
    var circlefriendsnews;
    //获取用户个人信息
    function getUsersInfo(){
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + "/index.php/api/user/getUsersInfo",
            dataType:'jsonp',
            data: { uid: uid,token:token },
            success: function(data) {
                if(data.error_code == 0){
                    localStorage.replace_face = data.data.face;
                    localStorage.replace_nickname = data.data.nickname;
                    localStorage.replace_mobile = data.data.mobile;  
                    localStorage.replace_sex = data.data.sex;  
                    localStorage.replace_myimg = data.data.img;  
                    data.data.new_friend=='1'?$('.myfrands').html('我的好友<i></i>'):$('.myfrands').html('我的好友');
                    data.data.new_attention=='1'?$('.myattention').html('我的关注<i></i>'):$('.myattention').html('我的关注');
                    data.data.new_fans=='1' ? $('.myfans').html('我的粉丝<i></i>') :$('.myfans').html('我的粉丝');
                    if(data.data.new_article=='1'){
                        circlefriendsnews=1;
                        $('#circlefriends span').html('朋友圈<i class="friends-box-i"></i>')
                    }else{
                        circlefriendsnews=0;
                        $('#circlefriends span').html('朋友圈')
                    }
                    
                    data.data.new_date=='1'?$('.engagement').html('我的约会<i></i>'): $('.engagement').html('我的约会');
                    data.data.new_manager=='1'?$('.administer').html('经理人管理<i></i>'):$('.administer').html('经理人管理');
                    data.data.new_agent=='1'? $('.area').html('代理人管理<i></i>'):$('.area').html('代理人管理');
                    
                    if(data.data.new_friend=='0'&&data.data.new_attention=='0'&&data.data.new_date=='0'&&data.data.new_fans=='0'&&data.data.new_manager=='0'&&data.data.new_agent=='0'){
                        $('.mui-pull-left').html('')
                    }else{
                        $('.mui-pull-left').html('<i></i>')
                    }
                    if(localStorage.replace_face){
                        $('.mycenter-header .userimg > img').attr('src',DOMAIN_NAME+localStorage.replace_face);
                    }
                    data.data.img ?$('.share-img').css({'background-image':'url('+DOMAIN_NAME+data.data.img+')'}):$('.share-img').css({'background-image':'url(images/shear_bj.png)'});
                    $('.mycenter-header .user-title').html(localStorage.replace_nickname);
                    if(localStorage.replace_sex == 'man'){
                        $('.mycenter-header .age').removeClass('woman').addClass('man');
                    }else{
                        $('.mycenter-header .age').removeClass('man').addClass('woman');
                    }
                    $('.mycenter-header .user-message').html('我的身价：好友 '+data.data.friend_cost+'<i class="st"></i>约会 '+data.data.date_cost+'');
                    $('.mycenter-header .grade').html(data.data.level+'级用户');
                    $('.mycenter-header .current_level').html('LV'+data.data.level);
                    $('.mycenter-header .next_level').html('LV'+(data.data.level+1));
                    $('.mycenter-header .articlecharm-em').css('width',data.data.exp/data.data.level_exp*100+'%');
                    var cha ;
                    if(data.data.level_up_exp<0){
                        cha = ',未完成视频认证，无法升级';
                    }else if(data.data.level_up_exp>=0){
                        cha = '，离升级还差：'+data.data.level_up_exp;
                    }else{
                        cha = '，离升级还差：0';
                    }
                    $('.mycenter-header .user-text-sis').html('我的魅力值：'+data.data.exp+ cha );
                    $('#notecase > span').html(data.data.balance+'币');
                    $('#notecase2 > span').html(data.data.temporary_balance+'币');
                    if(data.data.is_vip){
                        $('#membercenter > span').html(new Date(data.data.vip_time*1000).format('yyyy-MM-dd')+'到期');
                        $('.search').addClass('active');
                    }else{
                        $('#membercenter > span').html('普通用户');
                        $('.search').removeClass('active');
                    }
                    if(data.data.voice_signature){
                        $('.con-voice-img').attr('data-voice',DOMAIN_NAME+data.data.voice_signature);
                        $('.con-voice-img').css({display:'block'})
                        $('.voice-em').css({display:'none'})
                    }
                    if(data.data.manager_uid&&data.data.date_status==3){
                        $('.mymanager').html('我的经理人:'+data.data.parent_nickname+'<span class="open" data-pid="'+data.data.manager_uid+'">解绑</span>')
                    }else if(data.data.date_status==3){
                        $('.mymanager').html('我的经理人:平台<span class="open">解绑</span>')
                    }else{
                        $('.mymanager').html('我的经理人:无<span class="open"></span>');
                    }
                    if(data.data.personal_status == 0){
                        $('#attestation > span').html('未认证');
                    }else if(data.data.personal_status == 1){
                        $('#attestation > span').html('审核中');
                    }else if(data.data.personal_status == 2){
                        $('#attestation > span').html('已拒绝');
                    }else if(data.data.personal_status == 3){
                        $('#attestation > span').html('已认证');
                    }
                    if(data.data.date_status == 0){
                        $('#dataattestation > span').html('未认证');
                    }else if(data.data.date_status == 1){
                        $('#dataattestation > span').html('审核中');
                    }else if(data.data.date_status == 2){
                        $('#dataattestation > span').html('已拒绝');
                    }else if(data.data.date_status == 3){
                        $('#dataattestation > span').html('已认证');
                    }
                    if(data.data.manager_status == 0){
                        $('#handler > span').html('未申请');
                    }else if(data.data.manager_status == 1){
                        $('#handler > span').html('审核中');
                    }else if(data.data.manager_status == 2){
                        $('#handler > span').html('已拒绝');
                    }else if(data.data.manager_status == 3){
                        $('#handler > span').html('已认证');
                    }
                    if(data.data.agent_status == 0){
                        $('#agency > span').html('未申请');
                    }else if(data.data.agent_status == 1){
                        $('#agency > span').html('审核中');
                    }else if(data.data.agent_status == 2){
                        $('#agency > span').html('已拒绝');
                    }else if(data.data.agent_status == 3){
                        $('#agency > span').html('已认证');
                    }
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }
            }
        });
    }
    
    var moveEndY = 0;
    var startY = 0;
    var r = null; 
    function chatRecord() {
        plus.device.vibrate( 500 );
        localStorage.startTime = (new Date()).valueOf();
        r = plus.audio.getRecorder(); 
        if ( r == null ) {
            plus.nativeUI.toast( "Device not ready!" );
            return; 
        } 
        r.record( {filename:"_doc/audio/",format: "amr"}, function (path) {
            if(localStorage.record == 'send'){
                if((localStorage.endTime - localStorage.startTime) > 1 * 1000){
                    upload(path);
                    localStorage.record = 'cancel';
                }else{
                    plus.nativeUI.toast('语音时间太短');
                }
            }

        }, function ( e ) {
            $('.voice-lading').css({display:'none'});
        });
    }
    function stopChatRecord() {
        localStorage.endTime = (new Date()).valueOf();
        localStorage.record = 'send';
        r.stop(); 
    }
    function cancelRecord(e){
        localStorage.endTime = (new Date()).valueOf();
        localStorage.record = 'cancel';
        r.stop(); 
    }

    //按住说话
    $(".voice-em").on("touchstart", function(e) {
        $('.ys-modal-loading').css({display:'block'})
        e.preventDefault();
        //按下时手指坐标
        startY = e.originalEvent.changedTouches[0].pageY;
        chatRecord();
        $('.voice-lading').css({display:'block'});
    });
    $(".voice-em").on('touchend', function(e) {
        //松开时手指坐标
        $('.voice-lading').css({display:'none'});
        moveEndY = e.originalEvent.changedTouches[0].pageY;
        Y = startY - moveEndY;
        //取消录音
        if(Y>20){
            cancelRecord()
            return false;
        }else{
            stopChatRecord()
        }
    })

    //上传
    function upload(files) {
        var task = plus.uploader.createUpload(DOMAIN_NAME + "/index.php/api/user/voiceSignatureEdit", {
            method: "POST",
            blocksize: 204800,
            priority: 100
        },function(t, status) { //上传完成
            if (status == 200) {
                var a = t.responseText;
                var b = /jsonpReturn\(([^]*?)\)/;
                var s = a.match(b)[1];
                var obj = s.replace(/\\/g, "")
                var img = $.parseJSON(obj);
                mui.toast('上传成功');
                $('.voice-em').css({display:'none'})
                $('.con-voice-img').attr('data-voice',DOMAIN_NAME+img.data);
                $('.con-voice-img').css({display:'block'})
                getUsersInfo();
            }else{
                mui.toast('上传失败',{ duration:2000, type:'div' });
            }
        });
        task.addData("uid", uid);
        task.addFile(files, {key: 'voice'});
        task.start();
    }
    

    //获取用户列表信息
    function getlist(othis,opage){
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + "/index.php/api/user/getUsersList",
            dataType:'jsonp',
            data: { uid: uid,token :token},
            success: function(data) {
                if(data.error_code == 0){
                    olist ='';
                    if(othis==null){
                        if(opage==1){
                            olist +='<div class="box box-one">'
                        }else if(opage ==2 ){
                            olist +='<div class="box box-two"> '
                        }else if(opage ==3 ){
                            olist +='<div class="box box-three"> '
                        }
                    }
                    for ( var i =0 ; i<data.data.length ; i++) {
                        var otface = data.data[i].face ?  DOMAIN_NAME+data.data[i].face :'images/default_img.jpg';
                        olist +='<a class="mp-user" data-id="'+data.data[i].uid+'" href="javascript:">'
                                +'<div class="box-img demo">'
                                    +'<img src="'+otface+'" />'
                                    +'<div class="friends-box">'
                                        +'<div class="img-amount">'+data.data[i].files_num+'</div>';
                        if(data.data[i].dynamic){olist+='<div class="friends"></div>'}
                        olist +='</div></div><div class="box-text">'
                               +'<div class="text-title">'+data.data[i].nickname+'</div>'
                               +'<span class="age '+data.data[i].sex+'">'+data.data[i].age+'岁</span>';
                        if(data.data[i].level){olist+='<span class="sexs">'+data.data[i].level+'级魅力</span>'}
                        if(data.data[i].vip){olist+='<div class="vip">VIP</div></div></a>'}else{olist+='</div></a>'};
                    }
                    
                    if(othis==null){
                        olist +='</div>';
                        $('.index-box').append(olist)
                    }else{
                        othis.html(olist);
                    }
                    olist='';
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }else{
                    
                }
            }
        });
    }
    //解绑
    function parentopen(submitid){
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + "/index.php/api/user/dateUnbindApply",
            dataType:'jsonp',
            data: { uid: uid,token :token,submit_to:submitid,},
            success: function(data) {
                if(data.error_code == 0){
                    mui.toast('提交解绑成功,请等待审核！',{ duration:2000, type:'div' });
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }else{
                    mui.toast(data.error_msg,{ duration:2000, type:'div' });
                }
            }
        });
    }
    
    //获取cdk
    function convertcdk(ocdk){
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + "/index.php/api/user/cdkExchange",
            dataType:'jsonp',
            data: { uid: uid,token :token,cd_key:ocdk,},
            success: function(data) {
                if(data.error_code == 0){
                    mui.confirm(''+data.error_msg+'','获得的内容',['确定','取消'],null,'div');
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }else{
                    mui.confirm('您的CDK兑换码有错，请重新输入','提示',['确定','取消'],null,'div');
                }
            }
        });
    }

    //邀请好友
    function invitefrands(){
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + "/index.php/api/user/inviteFriends",
            dataType:'jsonp',
            data: { uid: uid,token :token},
            success: function(data) {
                if(data.error_code == 0){
                    $('.share-box .user-img').html('<img class="user-imgs" src="'+DOMAIN_NAME+data.data.qr_code+'">')
                    $('.share-box .share-name').text('昵称：'+data.data.nickname+'');
                    $('.share-box .share-id').text('YP号：'+data.data.uid+'');
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }else{
                }
            }
        }); 
    }
    var leftnew=0,rightnew=0;
    //聊天信息
    function message(){
        updateNoticeNum()
        leftnew=0,rightnew=0;
        //系统
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + "/index.php/api/notice/newSystemNotices",
            dataType:'jsonp',
            data: {uid:uid,token:token,},
            success: function(data) {
                if(data.error_code == 0){
                    var osum = data.data.sum>99 ? '99+': data.data.sum==0? ' ' : data.data.sum;
                    if(data.data.sum>0){
                        leftnew+= parseInt(data.data.sum);
                    }
                    $('.message .scroll2 .box .setmsg .time').text(timesub(data.data.send_time));
                    $('.message .scroll2 .box .setmsg p').text(data.data.content);
                    $('.message .scroll2 .box .setmsg span').text(osum);
                    onews();
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }
            }  
        });
        //好友
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + "/index.php/api/chat/usersNewChat",
            dataType:'jsonp',
            data: {uid:uid,token:token,},
            success: function(data) {
                if(data.error_code == 0){
                    var msghtml='',num='';
                    for(var i=0 ; i<data.data.length ; i++){
                        var osnum = data.data[i].num>99 ? '99+': data.data[i].num==0? ' ' : data.data[i].num;
                        switch(data.data[i].type)
                        {
                        case "text":
                            ocontent = data.data[i].content.replace(/\.\?\./g,"'");
                            break;
                        case 'img':
                            ocontent ="【图片】";
                            break;
                        case 'radio':
                            ocontent ="【语音】";
                            break;
                        case 'voice':
                            ocontent ="【个性语音】";
                            break;
                        case 'video':
                            ocontent ="【视频】";
                            break;
                        case 'gift':
                            ocontent ="【礼物】";
                            break;
                        case 'pieces':
                            ocontent ="【碎片】";
                            break;
                        default:
                            ocontent ="【名片】";
                        }
                        var newtime = timesub(data.data[i].send_time);
                        if(data.data[i].num>0){
                            leftnew +=parseInt( data.data[i].num );
                        }
                        msghtml +='<li class="chatli" data-id="'+data.data[i].uid+'"><div class="tab-img"><img onerror="imgExists(this)" src="'+DOMAIN_NAME+data.data[i].face+'"/>'
                                +'<span>'+osnum+'</span>'
                                +'</div><div class="box-text"><div class="text-title">'+data.data[i].nickname+'</div>'
                                +'<div class="chat-list"><p>'+ocontent+'</p></div></div><div class="time">'+newtime+'</div><i class="delect"></i></li>';
                    }
                    $('.chat-box').html(msghtml);
                    onews();
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }else{
                    $('.chat-box').html('');
                }
            }  
        });
        //约会信息
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + "/index.php/api/chat/usersNewStrangerChat",
            dataType:'jsonp',
            data: {uid:uid,token:token,},
            success: function(data) {
                if(data.error_code == 0){
                    var msghtml='',num='';
                    for(var i=0 ; i<data.data.length ; i++){
                        var osnum = data.data[i].num>99 ? '99+': data.data[i].num==0? ' ' : data.data[i].num;
                        switch(data.data[i].type)
                        {
                        case "text":
                            ocontent = data.data[i].content.replace(/\.\?\./g,"'");
                            break;
                        case 'img':
                            ocontent ="【图片】";
                            break;
                        case 'radio':
                            ocontent ="【语音】";
                            break;
                        case 'voice':
                            ocontent ="【个性语音】";
                            break;
                        case 'video':
                            ocontent ="【视频】";
                            break;
                        case 'gift':
                            ocontent ="【礼物】";
                            break;
                        case 'pieces':
                            ocontent ="【碎片】";
                            break;
                        default:
                            ocontent ="【名片】";
                        }
                        var newtime = timesub(data.data[i].send_time);
                        if(data.data[i].num>0){
                            rightnew += parseInt( data.data[i].num );
                        }
                        msghtml +='<li class="strangeli" data-id="'+data.data[i].uid+'" ord-id="'+data.data[i].date_id+'"><div class="tab-img"><img onerror="imgExists(this)" src="'+DOMAIN_NAME+data.data[i].face+'"/>'
                                +'<span>'+osnum+'</span>'
                                +'</div><div class="box-text"><div class="text-title">'+data.data[i].nickname+'</div>'
                                +'<div class="chat-list"><p>'+ocontent+'</p></div></div><div class="time">'+newtime+'</div><i class="delect"></i></li>';
                    }
                    $('.message .scroll3 .box').html(msghtml);
                    onews()
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }else{
                    $('.message .scroll3 .box').html('');
                }
            }  
        });
    }

/**
 * @消息总数
 * @param cb
 */
function getNoticeNum(cb){
  $.ajax({
    type: "post",
    url: DOMAIN_NAME + '/index.php/api/notice/getNoticeNum',
    dataType:'jsonp',
    data: { uid: uid,token:token},
    success: function(data) {
      if (data.error_code == 0) {
        if (cb && typeof cb === 'function'){
          cb(data.data)
        }
      } else {
        // 静默失败
      }
    }
  })
}

/**
 * @Desc 更新消息总数
 */
function updateNoticeNum(){
  getNoticeNum(function(num) {
    if (num > 0) {
      if (num > 99) {
          num = '99+'
      }
      $('.message-header span').text("("+ num +")")
      $('.mui-pull-right').html('<i></i>')
    } else {
      $('.message-header span').text("")
      $('.mui-pull-right').html('')
    }
    plus.runtime.setBadgeNumber(num)
  })
}

/**
 * @系统消息已读
 * @param cb
 */
function setRead(cb){
  $.ajax({
    type: "post",
    url: DOMAIN_NAME + '/index.php/api/notice/setRead',
    dataType:'jsonp',
    data: { uid: uid,token:token},
    complete: function(data) {
      if (cb && typeof cb === 'function'){
        cb()
      }
    }
  })
}

/**
 * @朋友圈消息已读
 */
function articleRead(cb){
  $.ajax({
    type: "post",
    url: DOMAIN_NAME + '/index.php/api/user/articleRead',
    dataType:'jsonp',
    data: { uid: uid,token:token},
    complete: function(data) {
      if (cb && typeof cb === 'function'){
        cb()
      }
    }
  })
}

    function onews(){
        leftnew >0 ? $('.message .tab a').eq(0).find('span i').css({display:'block'}): $('.message .tab a').eq(0).find('span i').css({display:'none'});
        rightnew >0 ? $('.message .tab a').eq(1).find('span i').css({display:'block'}) : $('.message .tab a').eq(1).find('span  i').css({display:'none'});
    }
    /**
     * 
     * 语音播放
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    var p =null;
    var oarr=common.browserType();
    $('.index').on('tap','.con-voice-img',function(){
        var vic = $(this).attr('data-voice');
        if(oarr.ios){ 
            if(p != null){
                p.stop();
            }
            var dtask = plus.downloader.createDownload(vic, {}, function ( d, status ) {
            // 下载完成
                if ( status == 200 ) { 
                    if ( plus.audio == undefined ) {
                        alert( "Device not ready!" );
                    }
                    p = plus.audio.createPlayer(d.filename);
                    p.play( function () {
                        p = null;
                    }, function ( e ) {
                       plus.nativeUI.toast("播放错误: " + e.message);
                    });
                    
                } else {
                    alert( "网络错误"); 
                }  
            });
            dtask.start();                  
        }else{
            common.playAudio(vic);
        }
    })//语音播放
    
    /**
     * 
     * 删除单个好友记录
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */   
    function chatstate(fuid,statedate_id,othis){
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + '/index.php/api/chat/friendChatDel',
            dataType:'jsonp',
            data: { uid: uid,token:token,friend_uid:fuid,date_id:statedate_id},
            success: function(data) {
                if(data.error_code == 0){
                    message();
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }
            }
        });
    }
    
connect()

var shares = null;
// 监听plusready事件  
document.addEventListener("plusready", function() {
    // 扩展API加载完毕，现在可以正常调用扩展API
    plus.share.getServices(function(s) {
        shares = s;
    }, function(e) {
        mui.toast('获取分享服务列表失败：',{ duration:2000, type:'div' });
        // mui.alert("获取分享服务列表失败：" + e.message, '提示', '确定', function() {
        //         }, 'div');
        
    });
}, false);
/**
 * 分享操作
 * @param {plus.share.ShareService} s
 */
var Share={};
Share.info = {
    id: '',
    name: '',
    head_image: DOMAIN_NAME + "/replace/images/logo.png",
    introduce: ''
};
var sharecount = 0;
function shareAction(s,ex) {
    if(!s) {
        return;
    }
    if(s.authenticated) {
        shareMessage(s,ex);
    } else {
        s.authorize(shareMessage, function(e) {
            mui.toast('未进行认证',{ duration:2000, type:'div' });
            // mui.alert("未进行认证", '提示', '确定', function() {
            //     }, 'div');
        });
    }
}
/**
 * 发送分享消息
 * @param {plus.share.ShareService} s
 */
function shareMessage(s,ex) {
    plus.nativeUI.showWaiting();
    setTimeout(plus.nativeUI.closeWaiting,5000);//TODO 5秒后自动关闭等待，否则如果用户分享出去后选择‘留在微信’，再手动回到app的时候，waiting无法关闭
    var msg = {
        extra: {
            scene: ex
        }
    };
    msg.href = DOMAIN_NAME+"/index.php/wap/user/regist?uid="+uid;
    msg.title = '【换一批】';
    msg.content =localStorage.replace_nickname+' 通过【换一批】向你发出了注册邀请';
    //取本地图片
    var img = 'images/logo.png';
    msg.thumbs = '';
    if (sharecount > 0) {
        msg.thumbs = '';
    }
    s.send(msg, function() {
        plus.nativeUI.closeWaiting();
        sharwe();
    }, function(e) {
        plus.nativeUI.closeWaiting();           
        if (e.code == -2) {
            plus.nativeUI.toast('已取消分享', {
                verticalAlign: 'center'
            });
            sharecount = 0;
        } else if (e.code == -3 || e.code == -8) {
            if (++sharecount < 2) {
                //TODO 分享失败可能是图片过大的问题，递归取默认图片重新分享
                shareMessage(s, ex);
            } else {
                sharecount = 0;
                plus.nativeUI.toast('分享失败', {
                    verticalAlign: 'center'
                });
            }
        }else{
            console.error('分享失败:'+JSON.stringify(e))
        }
        console.log("分享到\"" + s.description + "\"失败: " + e.code + " - " + e.message);
    });
}

$('.share-link').on('tap', 'a', function() {
    if($(this).hasClass('wechat')) {
        shareAction(shares[0],'WXSceneSession');
    }else if($(this).hasClass('Circle')){
        shareAction(shares[0],'WXSceneTimeline');
    }
});

function sharwe(){
    $.ajax({
        type: "post",
        url: DOMAIN_NAME + "/index.php/api/user/getShareExp",
        dataType:'jsonp',
        data: {uid:uid,token:token,},
        success: function(data) {
            mui.toast('分享成功！',{ duration:2000, type:'div' });
            if(data.error_code == 0){
            }else if(data.error_code == 1001){
                setTimeout(function(){
                    exitlogin();
                },1000);
            }
        }  
    });
}

var bool=true;
localStorage.camopen="true";
//后台切换
document.addEventListener("plusready", onPlusReady, false); 
function onPlusReady(){
    document.addEventListener("resume", otre, false);
    document.addEventListener("pause", function(){
        bool=true;
    });
}

function otre(){
    connect();
    if( (localStorage.camopen=='true') && bool ){
        var t1="welcome";
        var t2="guide";
        var wvs=plus.webview.getDisplayWebview();
        var rag =wvs[0].getURL();
        var op =new RegExp(t1).test(rag);
        var op2 =new RegExp(t2).test(rag);
        if((op==false)&&(op2==false)&&(localStorage.screens!='false')){
            localStorage.welcome='resume';
            pgwelcome();
        }
    }
    localStorage.camopen='true';
    bool=false;
}

